﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using ProjectEuler.Extensions;

namespace ProjectEuler.Problems
{
    [EulerProblem(38, 932718654)]
    [Description("What is the largest 1 to 9 pandigital that can be formed by multiplying a fixed number by 1, 2, 3, ... ?")]
    internal sealed class Problem038 : EulerProblem
    {
        public override Object Solve()
        {
            var sb = new StringBuilder(9);
            var result = 0;

            for (var n = 9; n >= 2; n--)
            {
                var max = Math.Pow(10, Math.Ceiling(9.0 / n));

                for (var i = 1; i <= max; i++)
                {
                    sb.Length = 0;

                    for (var c = 1; c <= n; c++)
                    {
                        sb.Append(i * c);
                    }

                    if (IsPandigital(sb))
                    {
                        result = Math.Max(result, Int32.Parse(sb.ToString()));
                    }
                }
            }

            return result;
        }

        private Boolean IsPandigital(StringBuilder sb)
        {
            if (sb.Length == 9)
            {
                var digits = new BitArray(9);

                for (int i = 0; i < sb.Length; i++)
                {
                    if ((sb[i] >= '1') && (sb[i] <= '9'))
                    {
                        digits[sb[i] - '1'] = true;
                    }
                }

                return digits.AllTrue();
            }

            return false;
        }
    }
}
